﻿@*
    工艺管理页面
*@
@{
    var isEmbed = Context?.Request?.Query["embed"].ToString() == "1";
    Layout = isEmbed ? null : "_Layout";
    ViewData["Title"] = "工艺管理";
}
<link href="~/css/site.css" rel="stylesheet" />
<link href="~/layui/css/layui.css" rel="stylesheet" />
<script src="~/js/site.js"></script>
<script src="~/layui/layui.js"></script>
<script src="~/js.cookie.js"></script>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>

<style>
    /* 查询区域样式 */
    .search-section {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .search-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
        padding-bottom: 10px;
        border-bottom: 2px solid #1e88e5;
    }
    
    .search-form {
        display: flex;
        align-items: center;
        gap: 20px;
        flex-wrap: wrap;
    }
    
    .search-item {
        display: flex;
        align-items: center;
        gap: 8px;
    }
    
    .search-item label {
        font-weight: 500;
        color: #333;
        min-width: 80px;
    }
    
    .search-item input {
        width: 200px;
        border-radius: 4px;
        border: 1px solid #ddd;
        padding: 8px 12px;
        transition: all 0.3s ease;
    }
    
    .search-item input:focus {
        border-color: #1e88e5;
        box-shadow: 0 0 0 2px rgba(30,136,229,0.2);
        outline: none;
    }
    
    .search-buttons {
        display: flex;
        gap: 15px;
        margin-left: auto;
    }
    
    .search-btn {
        background: #1e88e5;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 14px;
    }
    
    .search-btn:hover {
        background: #1565c0;
        transform: translateY(-1px);
    }
    
    .add-btn {
        background: #4caf50;
        color: white;
        border: none;
        padding: 8px 20px;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s ease;
        font-size: 14px;
    }
    
    .add-btn:hover {
        background: #388e3c;
        transform: translateY(-1px);
    }
    
    /* 表格容器样式 */
    .table-container {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        padding: 20px;
    }
    
    /* 响应式设计 */
    @@media (max-width: 768px) {
        .search-form {
            flex-direction: column;
            align-items: stretch;
        }
        
        .search-item {
            flex-direction: column;
            align-items: stretch;
        }
        
        .search-item input {
            width: 100%;
        }
        
        .search-buttons {
            margin-left: 0;
            justify-content: center;
        }
    }
    
    /* 序号列样式 */
    .sequence-column {
        text-align: center;
        font-weight: 600;
        color: #495057;
        background-color: #f8f9fa;
        min-width: 60px;
    }
    
    /* 表格样式优化 */
    .layui-table th {
        background-color: #f8f9fa;
        font-weight: 600;
        color: #495057;
        text-align: center;
        padding: 12px 8px;
        border: 1px solid #e0e0e0;
    }
    
    .layui-table td {
        text-align: center;
        padding: 12px 8px;
        border: 1px solid #e0e0e0;
        vertical-align: middle;
    }
    
    /* 分页组件样式 */
    .table-container {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 12px rgba(0,0,0,0.1);
        padding: 20px;
        margin-bottom: 20px;
    }
    
    #demo-laypage-all {
        margin-top: 20px;
        text-align: center;
    }
    
    /* 确保分页组件可见 */
    .layui-laypage {
        display: block !important;
        margin: 20px 0;
    }
</style>

<!-- 查询区域 -->
<div class="search-section">
    <div class="search-title">
        <i class="layui-icon layui-icon-search" style="margin-right: 8px; color: #1e88e5;"></i>
        工艺查询
    </div>
    
    <div class="search-form">
        <div class="search-item">
            <label>工艺单号：</label>
            <input type="text" id="craftsCode" placeholder="请输入工艺单号" />
        </div>
        
        <div class="search-item">
            <label>工艺名称：</label>
            <input type="text" id="craftsName" placeholder="请输入工艺名称" />
        </div>
        
        <div class="search-buttons">
            <button class="search-btn" onclick="searchCrafts()">
                <i class="layui-icon layui-icon-search"></i>
                查询
            </button>
            <button class="add-btn" onclick="addCrafts()">
                <i class="layui-icon layui-icon-add-1"></i>
                添加工艺
            </button>
        </div>
    </div>
</div>

<!-- 表格容器 -->
<div class="table-container">
    <table class="layui-table">
        <thead>
            <tr>
                <th>序号</th>
                <th>工艺编号</th>
                <th>工艺名称</th>
                <th>工序数量</th>
                <th>负责人</th>
                <th>所属部门</th>
                <th>状态</th>
                <th>备注</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="tb"></tbody>
    </table>
    <div id="demo-laypage-all">
        <p style="text-align: center; color: #999; padding: 10px;">分页组件加载中...</p>
    </div>
</div>

<script>
    $(function(){
        console.log('页面加载完成，开始初始化');
        shows();
    })

    var PageIndex=1;
    var PageSize=5;
    var TotalCount=0;
    var TotalPage=0;

    // 查询工艺
    function searchCrafts() {
        var craftsCode = $('#craftsCode').val().trim();
        var craftsName = $('#craftsName').val().trim();
        
        console.log('查询条件:', { craftsCode, craftsName });
        
        // 重置分页
        PageIndex = 1;
        
        // 执行查询
        shows(craftsCode, craftsName);
    }
    
    // 添加工艺
    function addCrafts() {
        // 跳转到添加工艺页面
        window.location.href = '/Process/CraftsAdd';
    }

    function shows(craftsCode = '', craftsName = ''){
        // 构建查询参数
        var queryParams = `PageIndex=${PageIndex}&PageSize=${PageSize}`;
        if (craftsCode) {
            queryParams += `&craftsCode=${encodeURIComponent(craftsCode)}`;
        }
        if (craftsName) {
            queryParams += `&craftsName=${encodeURIComponent(craftsName)}`;
        }
        
        $.ajax({
            url: 'http://localhost:5161/api/Process/CraftsQuery?' + queryParams,
            dataType:'json',
            type:'get',
            contentType:'application/json',
            async:false,
            success:res=>{
                console.log(res);
                $("#tb").empty();
                TotalCount=res.data.totalCount
                TotalPage=res.data.totalPages
                
                // 重新渲染分页组件
                renderPagination();

                $(res.data.list).each(function(index){
                    var statusText = this.craftsStatus == false ? "启用" : "禁用";
                    var statusClass = this.craftsStatus == false ? "layui-bg-green" : "layui-bg-red";
                    var sequenceNumber = index + 1; // 自动生成序号，从1开始
                    
                    // 根据departId显示对应的部门名称
                    var departmentName = '';
                    if(this.departId == 1){
                        departmentName = "生产部";
                    } else if(this.departId == 2){
                        departmentName = "质检部";
                    } else if(this.departId == 3){
                        departmentName = "技术部";
                    } else {
                        departmentName = this.departId || '-';
                    }

                    $("#tb").append(`
                       <tr data-crafts='${JSON.stringify(this).replace(/'/g, "&apos;")}'>
                        <th>${sequenceNumber}</th>
                        <th>${this.craftsCode}</th>
                        <th>${this.craftsName}</th>
                        <th>${this.haveProcess}</th>
                        <th>${this.responsibilityName || '-'}</th>
                        <th>${departmentName}</th>
                        <th><span class="layui-badge ${statusClass}">${statusText}</span></th>
                        <th>${this.note || '-'}</th>
                        <th>
                            <button class="layui-btn layui-btn-sm" onclick="editCrafts(this)" data-id="${this.id}">编辑</button>
                            <button class="btn btn-danger layui-btn-sm" onclick="deleteCrafts(this)" data-id="${this.id}">删除</button>
                            <button class="layui-btn layui-btn-normal layui-btn-sm" onclick="viewCraftsDetails(this)" data-id="${this.id}">详情</button>
                        </th>
                       </tr>
                    `)
                })
                
                // 确保序号正确
                updateTableSequence();
            },
            error: function(xhr, status, error) {
                console.error('查询失败:', error);
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('查询失败，请重试', {icon: 2, time: 2000});
                });
            }
        })
    }

      //分页
    function renderPagination(){
        console.log('开始渲染分页组件');
        console.log('TotalCount:', TotalCount, 'PageSize:', PageSize, 'PageIndex:', PageIndex);
        
        // 只有当有数据时才渲染分页
        if (TotalCount > 0) {
            layui.use(['laypage'], function(){
                var laypage = layui.laypage;
                
                // 完整显示
                laypage.render({
                    elem: 'demo-laypage-all', // 元素 id
                    count: TotalCount, // 数据总数
                    limit: PageSize,
                    curr: PageIndex,
                    limits: [5, 10, 15, 20],
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
                    jump: function(obj, first){
                        console.log('分页跳转:', obj, 'first:', first);
                        if (!first) {
                            PageIndex = obj.curr;
                            PageSize = obj.limit;
                            console.log('更新分页参数 - PageIndex:', PageIndex, 'PageSize:', PageSize);
                            shows();
                        }
                    }
                });
                
                console.log('分页组件渲染完成');
            });
        } else {
            console.log('没有数据，不渲染分页组件');
            $('#demo-laypage-all').html('<p style="text-align: center; color: #999; padding: 20px;">暂无数据</p>');
        }
    }
    
    // 编辑工艺
    function editCrafts(button) {
        var id = $(button).data('id');
        var row = $(button).closest('tr');
        var craftsData = row.data('crafts');
        
        console.log('编辑工艺ID:', id);
        console.log('完整工艺数据:', craftsData);
        
        // 跳转到CraftsAdd.cshtml的编辑模式，并传递完整数据
        var url = `/Process/CraftsAdd?id=${id}`;
        
        // 将工艺数据存储到sessionStorage中，供编辑页面使用
        if (craftsData) {
            sessionStorage.setItem('editCraftsData', JSON.stringify(craftsData));
        }
        
        window.location.href = url;
    }
    
    // 修改工艺的API调用 - 接收完整的工艺数据作为参数，IsUpdOrDel=false表示修改
    function updateCraftsById(craftsData) {
        layui.use('layer', function(){
            var layer = layui.layer;
            var loadIndex = layer.load(1, {shade: [0.3, '#000']});
            
            // 添加修改标识字段
            var requestData = {
                ...craftsData,
                IsUpdOrDel: false  // false表示修改操作
            };
            
            console.log('准备修改工艺数据:', requestData);
            
            $.ajax({
                url: 'http://localhost:5161/api/Process/CraftsEdit',
                dataType: 'json',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(res) {
                    layer.close(loadIndex);
                    if (res.code === 200) {
                        layer.msg('修改成功', {icon: 1, time: 1500});
                        // 刷新列表
                        shows();
                    } else {
                        layer.msg('修改失败：' + res.message, {icon: 2, time: 3000});
                    }
                },
                error: function() {
                    layer.close(loadIndex);
                    layer.msg('修改失败，请重试', {icon: 2, time: 3000});
                }
            });
        });
    }
    
    // 删除工艺
    function deleteCrafts(button) {
        // 获取整行数据
        var row = $(button).closest('tr');
        var craftsData = row.data('crafts');
        var id = $(button).data('id');
        
        console.log('删除工艺ID:', id);
        console.log('完整工艺数据:', craftsData);
        
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.confirm('确定要删除这个工艺吗？', {
                icon: 3,
                title: '确认删除'
            }, function(index){
                layer.close(index);
                // 执行删除逻辑，传递完整的工艺数据
                deleteCraftsById(craftsData);
            });
        });
    }
    
    // 查看工艺详情
    function viewCraftsDetails(button) {
        var id = $(button).data('id');
        var row = $(button).closest('tr');
        var craftsData = row.data('crafts');
        console.log('查看工艺详情ID:', id);
        console.log('查看工艺详情-整行数据:', craftsData);
        console.log('查看工艺详情-数据类型:', typeof craftsData);
        console.log('查看工艺详情-数据JSON:', JSON.stringify(craftsData));
        
        // 将当前行数据缓存，供详情页直接回显
        if (craftsData) {
            try { 
                sessionStorage.setItem('viewCraftsData', JSON.stringify(craftsData)); 
                console.log('工艺数据已成功存储到sessionStorage');
                console.log('存储的数据:', sessionStorage.getItem('viewCraftsData'));
            } catch(e) { 
                console.error('存储工艺数据到sessionStorage失败:', e); 
            }
        } else {
            console.error('未获取到工艺数据，无法存储');
        }
        
        // 跳转到详情页面
        window.location.href = `/Process/CraftsDetails?id=${id}`;
    }
    
    // 删除工艺的API调用 - 接收完整的工艺数据作为参数，IsUpdOrDel=true表示删除
    function deleteCraftsById(craftsData) {
        layui.use('layer', function(){
            var layer = layui.layer;
            var loadIndex = layer.load(1, {shade: [0.3, '#000']});
            
            // 添加删除标识字段
            var requestData = {
                ...craftsData,
                IsUpdOrDel: true  // true表示删除操作
            };
            
            console.log('准备删除工艺数据:', requestData);
            
            $.ajax({
                url: 'http://localhost:5161/api/Process/CraftsEdit',
                dataType: 'json',
                type: 'post',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(res) {
                    layer.close(loadIndex);
                    if (res.code === 200) {
                        layer.msg('删除成功', {icon: 1, time: 1500});
                        // 刷新列表
                        shows();
                    } else {
                        layer.msg('删除失败：' + res.message, {icon: 2, time: 3000});
                    }
                },
                error: function() {
                    layer.close(loadIndex);
                    layer.msg('删除失败，请重试', {icon: 2, time: 3000});
                }
            });
        });
    }
    

    
    // 清空查询条件
    function clearSearch() {
        $('#craftsCode').val('');
        $('#craftsName').val('');
        // 重新加载数据
        PageIndex = 1;
        shows();
    }
    

    
    // 重新计算表格序号
    function updateTableSequence() {
        $('#tb tr').each(function(index) {
            var sequenceNumber = index + 1;
            $(this).find('th:first').text(sequenceNumber);
        });
        console.log('表格序号已更新');
    }
    

</script>